package com.cysyz.mylib.utils.tree.impl;

import com.cysyz.mylib.utils.tree.TreeAble;
import com.cysyz.mylib.utils.tree.TreeBuilder;
import com.cysyz.mylib.utils.tree.exception.TreeBuilderException;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.*;

@Component
public class TreeBuilderImpl implements TreeBuilder {
    @Override
    public <T extends TreeAble> List<T> generateMultiWayTree(Class<T> clazz, Collection<T> nodeList) {
        List<T> rootList = new ArrayList<T>();

        if (nodeList != null) {
            // 节点列表（散列表，用于临时存储节点对象）
            HashMap<Serializable, T> nodemap = new HashMap<Serializable, T>();
            // 根据结果集构造节点列表（存入散列表）
            for (Iterator<T> it = nodeList.iterator(); it.hasNext();) {
                T node = it.next();
                nodemap.put(node.getId(), node);
            }
            // 构造无序的多叉树
            Set<Map.Entry<Serializable, T>> entrySet = nodemap.entrySet();
            for (Iterator<Map.Entry<Serializable, T>> it = entrySet.iterator(); it.hasNext();) {
                T node = it.next().getValue();
                if (node.hasParent()) {
                    T parentNode = nodemap.get(node.getPid());
                    if (parentNode == null) {
                        throw new TreeBuilderException("在节点集合中无法找到某个节点的父节点，节点ID[" + node.getId() + "], 父节点ID["+node.getPid()+"]");
                    }
                    parentNode.addChild(node);
                } else {
                    rootList.add(node);
                }
            }
        }
        return rootList;
    }
}
